<?php

class Zip
{
	private $_basePath;
	
	public function __construct()
	{
		$this->_basePath = dirname(__FILE__);
	}
	
	/**
	 * 压缩
	 */
	public function compress() {
		$zip = new ZipArchive();
		$res = $zip->open('test.zip', ZipArchive::CREATE);
		$filels = array();
		$this->getFiles(dirname(__FILE__), $files);
		if ($res === true) {
			foreach ($files as $k => $v) {
				$zip->addFile($v, $k);
			}
			$zip->close();
		}
	}
	
	public function getFiles($dir, &$files, $pre = '')
	{
		if ($dh = opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				if ($file{0} == '.') {
					continue;
				}
				$filename = $dir . '/' . $file;
				if (empty($pre))
					$name = $file;
				else 
					$name = $pre . '/' . $file;
				if (is_dir($filename))
					$this->getFiles($filename, $files, $name);
				else 
					$files[$name] = $filename;
			}
			closedir($dh);
		}
	}
	
	/**
	 * 
	 * 创建测试文件
	 */
	public function createTestFile() {
		//文件数
		$fileNum = mt_rand(50, 100);
		for ($i = 0; $i < $fileNum; $i++) {
			//文件层次
			$fileDepth= mt_rand(0, 10);
			$time = time() . uniqid();
			$pathName = str_repeat($time . '/', $fileDepth);
			if (@mkdir($pathName, 0777, true))
				file_put_contents($pathName . $time . '.txt', $time);
		}
	}

}

$zip = new Zip();
//$zip->createTestFile();
$zip->compress();